//本地存储;思路：存储数据，然后拿出来；存 ——> 拿；
import React, {Component} from "react";
import {
	View,
	Text,
	Button,
	AsyncStorage,
} from "react-native";

export default class AsyncStorageExam extends Component {
	constructor(props) {
		super(props);
		this.state = {
			name: "",
		}
		this.doSomething = this.doSomething.bind(this);
	}
	//存储数据成功之后的回调；
	doSomething(error) {
		if(error != null) {
			console.log('error message:' + error.message);
			return;
		}
		alert("name保存成功!");
	}
	//进行数据存储操作；
	handleData = () => {
		AsyncStorage.setItem("name", "zongwu", this.doSomething);
	}

	//读取数据成功之后的回调；
	printRuslut = (error, result) => {
		if(error != null) {
			console.log('error message:' + error.message);
			return;
		}
		if(result == null) {
			return false;
		}
		this.setState({name: result})
	}
	//进行数据的读取操作；
	handleResult= () => {
		AsyncStorage.getItem("name", this.printRuslut);
	}

	//删除数据的回调；
	removeResult = (error) => {
		if(error != null) {
			console.log('error message:' + error);
			return;
		}
		alert("删除数据成功");
	}
	handleRemove = () => {
		AsyncStorage.removeItem('name', this.removeResult);
	}
	render() {
		return (
			<View>
				<Button 
					title="点击存储数据"
					onPress={this.handleData}
				/>
				<View style={{height: 20}}></View>
				<Button 
					title="点击获取数据"
					onPress={this.handleResult}
				/>
				<Text style={{height: 20}}>{this.state.name}</Text>
				<Button 
					title="点击删除数据"
					onPress={this.handleRemove}
				/>
			</View>
		);
	}
}

